#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        set<ListNode*> s1;
        while (head)
        {
            s1.insert(head);
            head = head->next;
            if (s1.find(head) != s1.end())
            {
                return head;
            }
        }

        return nullptr;
    }
};